package com.guchenbo.springboot.origin;

import com.guchenbo.springboot.DemoService;
import jakarta.annotation.Resource;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author guchenbo
 * @date 2022/6/27
 */
//@Component
//@ServerEndpoint("/ws/{account}")
public class DemoWebSocketEndpoint {
    protected static final Logger log = LoggerFactory.getLogger(DemoWebSocketEndpoint.class);

    private final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @Resource
    private DemoService demoService;

    @OnOpen
    public void onOpen(Session session, @PathParam("account") String account) throws IOException {
        sessionMap.putIfAbsent(account, session);
        sendMsg(account, demoService.count());
    }

    @OnMessage
    public void onMessage(String msg) {
        log.info("receive msg: {}", msg);
    }

    @OnClose
    public void onClose(@PathParam("account") String account) {
        sessionMap.remove(account);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("ws on error {}", session, throwable);
    }

    public void sendMsg(String account, String msg) throws IOException {
        Session session = sessionMap.get(account);
        if (session != null) {
            session.getBasicRemote().sendText(msg);
        }
    }
}
